<template>
  <div class="login-wrapper">
    <TitleBar title="CTP账户登录"></TitleBar>
    <div class="login-bg">
      <div class="login-mask"></div>
      <Card class="login-card" :bordered="false">
        <h2 class="login-title">账户登录</h2>
        <!-- 账号：183136 -->
        <Form :model="form" class="login-form">
          <Form.Item>
            <Select
              v-model:value="form.account"
              placeholder="选择交易账号"
              class="login-select"
              :dropdown-style="{ borderRadius: '8px' }"
              @change="onAccountChange"
              allow-clear
            >
              <Select.Option
                v-for="(config, key) in availableAccounts"
                :key="key"
                :value="key"
              >
                {{ key }}
              </Select.Option>
            </Select>
          </Form.Item>
          <Form.Item>
            <Select
              v-model:value="form.server"
              placeholder="选择CTP服务器"
              class="login-select"
              :dropdown-style="{ borderRadius: '8px' }"
              @change="onServerChange"
              :disabled="!form.account"
            >
              <Select.Option
                v-for="(config, key) in availableServers"
                :key="key"
                :value="key"
              >
                {{ config.name }}
              </Select.Option>
            </Select>
          </Form.Item>
          <!-- 密码：cb@12345678 -->
          <Form.Item>
            <InputPassword
              v-model:value="form.password"
              placeholder="请输入密码"
              class="login-input"
            />
          </Form.Item>
          <!-- <Form.Item class="login-remember-row">
            <Checkbox v-model:checked="form.remember">记住密码</Checkbox>
          </Form.Item> -->
          <Button type="primary" class="add-btn" @click="handleOpenAccountAdd">
            账号添加
          </Button>

          <!-- 服务器配置信息显示 -->
          <div class="server-info">
            <div class="server-info-title">当前服务信息</div>
            <div class="server-info-content">
              <div class="info-item" v-if="form.account">
                <span class="info-label">选择账号:</span>
                <span class="info-value">{{ form.account }}</span>
              </div>
              <!-- <div class="info-item" v-if="currentServerConfig">
                <span class="info-label">期货公司:</span>
                <span class="info-value">{{ currentServerConfig.brokerId }}</span>
              </div> -->
              <div class="info-item" v-if="currentServerConfig">
                <span class="info-label">交易前置:</span>
                <span class="info-value">{{ currentServerConfig.tradeFront }}</span>
              </div>
              <div class="info-item" v-if="currentServerConfig">
                <span class="info-label">行情前置:</span>
                <span class="info-value">{{ currentServerConfig.marketFront }}</span>
              </div>
              <div class="info-item" v-if="!form.account">
                <span class="info-label" style="color: #999">请先选择交易账号</span>
              </div>
            </div>
          </div>
          <Form.Item>
            <div class="login-buttons">
              <Button
                type="primary"
                class="login-btn"
                @click="onLogin"
                :loading="loginLoading"
                :disabled="loginLoading"
              >
                {{ loginLoading ? "登录中..." : "登 录" }}
              </Button>
            </div>
          </Form.Item>
        </Form>
      </Card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { Card, Form, Select, Button, InputPassword, message } from "ant-design-vue";
import { ref, onMounted, computed } from "vue";
import { useRouter } from "vue-router";
import { Window, LogicalPosition, primaryMonitor } from "@tauri-apps/api/window";
import { listen } from "@tauri-apps/api/event";
import { ctpService } from "../services/ctpService";
import { UserStorageService, UserInfo } from "../services/userStorage";
import { CtpConfigManager } from "../config/ctpConfig";
import { AccountConfigManager } from "../config/accountConfig";
import { useWindowManager } from "../composables/useWindowManager";
import { useMonitorManager } from "../composables/useMonitorManager";
import { useSoundManager } from "../composables/useSoundManager";
import TitleBar from "@/components/TitleBar.vue";

const router = useRouter();
const { openAccountAddWindow, listenAccountConfigUpdated } = useWindowManager();
const { getPrimaryMonitor } = useMonitorManager();
const { playLoginSuccessSound } = useSoundManager();

const form = ref({
  server: "",
  account: "",
  password: "",
  remember: false,
});

const loginLoading = ref(false);

// 响应式数据：所有可用的账号配置
const availableAccounts = ref<Record<string, any>>({});
// 响应式数据：所有可用的服务器配置
const availableServers = ref<Record<string, any>>({});

// 计算属性：获取当前选中的服务器配置
const currentServerConfig = computed(() => {
  const serverKey = form.value.server;
  return availableServers.value[serverKey] || null;
});

// 加载所有账号配置
const loadAllAccounts = async () => {
  try {
    const accounts = await AccountConfigManager.getAllAccounts();
    availableAccounts.value = accounts;
  } catch (error) {}
};

// 加载指定账号的服务器配置
const loadServersForAccount = async (accountName: string) => {
  try {
    // 获取预定义的服务器配置
    const predefinedServers = await CtpConfigManager.getAllServers();

    // 获取当前账号的配置
    const accountConfig = availableAccounts.value[accountName];

    if (accountConfig) {
      // 为当前账号创建服务器选项
      const accountServer = AccountConfigManager.accountToCtpConfig(accountConfig);
      const servers = {
        ...predefinedServers,
        [accountName]: accountServer,
      };
      availableServers.value = servers;
    } else {
      // 如果没有找到账号配置，只显示预定义服务器
      availableServers.value = predefinedServers;
    }
  } catch (error) {}
};

// 账号切换处理
const onAccountChange = async (accountName: string | null | undefined) => {
  if (accountName) {
    // 清空密码
    form.value.password = "";

    // 加载该账号对应的服务器配置
    await loadServersForAccount(accountName);

    // 自动选择该账号对应的服务器
    form.value.server = accountName;
  } else {
    // 如果清空账号选择，重置所有相关数据
    form.value.server = "";
    form.value.password = "";
    availableServers.value = {};

    // 清除选中的服务器配置
    CtpConfigManager.setSelectedServer("");
  }
};

// 服务器切换处理
const onServerChange = (serverKey: string) => {
  CtpConfigManager.setSelectedServer(serverKey);
};

// 打开账号添加窗口
const handleOpenAccountAdd = async () => {
  try {
    await openAccountAddWindow();
  } catch (error) {}
};

// 账号配置更新处理
const handleAccountConfigUpdated = async (accountConfig?: any) => {
  try {
    // 重新加载账号配置
    await loadAllAccounts();

    // 如果当前有选中的账号，重新加载其服务器配置
    if (form.value.account) {
      await loadServersForAccount(form.value.account);
    }
  } catch (error) {}
};

// 组件挂载时加载保存的用户信息和账号配置
onMounted(async () => {
  // 加载所有账号配置
  await loadAllAccounts();

  // 监听账号配置更新事件
  await listenAccountConfigUpdated((account) => handleAccountConfigUpdated(account));

  // 监听保存账号配置请求事件
  await listen("save-account-config", async (event: any) => {
    try {
      const { account } = event.payload;
      await AccountConfigManager.saveAccount(account);

      // 保存成功后立即更新配置列表
      await handleAccountConfigUpdated(account);
    } catch (error) {}
  });

  // 尝试恢复保存的用户信息
  const savedUserInfo = UserStorageService.getUserInfo();
  if (savedUserInfo) {
    // 检查保存的账号是否在可用账号列表中
    if (savedUserInfo.account && availableAccounts.value[savedUserInfo.account]) {
      form.value.account = savedUserInfo.account;
      form.value.password = savedUserInfo.password;
      form.value.remember = savedUserInfo.isRemembered;

      // 加载该账号对应的服务器配置
      await loadServersForAccount(savedUserInfo.account);

      // 设置服务器选择
      if (savedUserInfo.server && availableServers.value[savedUserInfo.server]) {
        form.value.server = savedUserInfo.server;
      } else {
        // 如果保存的服务器不存在，默认选择账号对应的服务器
        form.value.server = savedUserInfo.account;
      }

      CtpConfigManager.setSelectedServer(form.value.server);
    }
  }
});

const onLogin = async () => {
  try {
    // 验证表单
    const errors = UserStorageService.validateUserInfo(form.value);
    if (errors.length > 0) {
      message.error(errors[0]);
      return;
    }

    loginLoading.value = true;

    // 保存用户信息
    const userInfo: UserInfo = {
      account: form.value.account,
      password: form.value.password,
      server: form.value.server,
      isRemembered: form.value.remember,
      lastLoginTime: new Date().toISOString(),
    };
    UserStorageService.saveUserInfo(userInfo);

    // 获取CTP配置
    const ctpConfig = await UserStorageService.toCtpConfig(userInfo);

    // 创建行情API
    const mdResult = await ctpService.createMdApi();
    if (!mdResult.success) {
      throw new Error(mdResult.error || "创建行情API失败");
    }

    // 创建交易API
    const traderResult = await ctpService.createTraderApi();
    if (!traderResult.success) {
      throw new Error(traderResult.error || "创建交易API失败");
    }

    // 行情登录
    const mdLoginResult = await ctpService.mdLogin(ctpConfig);
    if (!mdLoginResult.success) {
      throw new Error(mdLoginResult.error || "行情登录失败");
    }

    // 交易登录
    const traderLoginResult = await ctpService.traderLogin(ctpConfig);
    if (!traderLoginResult.success) {
      throw new Error(traderLoginResult.error || "交易登录失败");
    }

    // 更新最后登录时间
    UserStorageService.updateLastLoginTime();

    // 播放登录成功提示音
    playLoginSuccessSound();

    // message.success('登录成功！');

    // 调整窗口大小和位置为小控制面板
    const curWindow = Window.getCurrent();
    await curWindow.setResizable(false);
    await curWindow.setDecorations(false); // 隐藏标题栏
    await curWindow.setTitle("交易控制面板");

    // 先隐藏窗口，避免在调整过程中闪烁
    await curWindow.hide();

    // 跳转到交易控制面板
    router.push("/trading-controller");

    // 等待路由跳转完成后设置位置
    await new Promise((resolve) => setTimeout(resolve, 100));

    // 获取屏幕尺寸并计算居中位置
    try {
      const monitor = await primaryMonitor();
      if (monitor) {
        const windowSize = await curWindow.outerSize();
        const screenWidth = monitor.size.width;
        const screenHeight = monitor.size.height;

        // 计算居中位置
        const centerX = Math.floor((screenWidth - windowSize.width) / 2);
        const centerY = Math.floor((screenHeight - windowSize.height) / 2);

        // 设置窗口位置到屏幕中央
        await curWindow.setPosition(new LogicalPosition(centerX, centerY));
      } else {
        // 如果无法获取屏幕信息，使用默认居中位置
        await curWindow.setPosition(new LogicalPosition(400, 300));
      }
    } catch (error) {
      // 如果获取屏幕信息失败，使用默认居中位置
      await curWindow.setPosition(new LogicalPosition(400, 300));
    }

    // 确保窗口不会自动居中，然后显示
    await curWindow.show();
  } catch (error) {
    const errorMsg =
      error instanceof Error ? error.message : "登录失败，请检查网络连接和账号信息";
    message.error(errorMsg);
  } finally {
    loginLoading.value = false;
  }
};
</script>

<style scoped>
.login-bg {
  height: calc(100vh - 32px);
  width: 100vw;
  position: relative;
  /* background: #0a1830 url("/your-bg-image.jpg") center/cover no-repeat; */
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.login-mask {
  position: absolute;
  inset: 0;
  background: rgba(10, 24, 48, 0.7);
  z-index: 1;
}

.login-card {
  position: relative;
  z-index: 2;
  width: 420px;
  background: rgb(92, 92, 192);
  padding: 36px 32px 28px 32px;
  border: none;
  height: 100%;
}

.login-title {
  color: #fff;
  text-align: center;
  margin-bottom: 32px;
  font-size: 30px;
  font-weight: 500;
  letter-spacing: 2px;
}

.login-form .ant-form-item {
  margin-bottom: 20px;
}

.login-select .ant-select-selector,
.login-input .ant-input,
.login-input .ant-input-password {
  border-radius: 8px !important;
  border: 1.5px solid #e2b23c !important;
  background: transparent !important;
  color: #fff !important;
  font-size: 16px;
  height: 44px;
}
.login-form {
  :deep(.ant-select-selector) {
    background: #fff !important;
  }
}

.login-select .ant-select-selector {
  color: #fff !important;
}

.login-input .ant-input,
.login-input .ant-input-password input {
  color: #fff !important;
  background: transparent !important;
}

.login-input .ant-input::placeholder,
.login-input .ant-input-password input::placeholder {
  color: #bbb !important;
}

.login-form .ant-checkbox-inner {
  border-radius: 4px;
  border: 1.5px solid #e2b23c;
  background: transparent;
}

.login-form .ant-checkbox-checked .ant-checkbox-inner {
  background-color: #e2b23c;
  border-color: #e2b23c;
}

.login-remember-row {
  margin-bottom: 10px;
}

.server-info {
  margin: 16px 0;
  padding: 12px;
  background: rgba(226, 178, 60, 0.1);
  border: 1px solid rgba(226, 178, 60, 0.3);
  border-radius: 8px;
}

.server-info-title {
  color: #e2b23c;
  font-size: 14px;
  font-weight: bold;
  margin-bottom: 8px;
  text-align: center;
}

.server-info-content {
  font-size: 12px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 4px;
}

.info-label {
  color: #bbb;
}

.info-value {
  color: #fff;
  font-family: monospace;
}

.login-buttons {
  display: flex;
  gap: 12px;
  margin-top: 8px;
}

.login-btn {
  flex: 2;
  background: #e2b23c !important;
  color: #222 !important;
  font-weight: bold;
  font-size: 20px;
  letter-spacing: 4px;
  border-radius: 8px;
  border: none;
  height: 48px;
  margin-top: 8px;
  box-shadow: 0 2px 8px rgba(226, 178, 60, 0.15);
}
.add-btn {
  background-color: #e2b23c;
  color: #222 !important;
}

.login-btn:focus,
.add-btn:focus,
.login-btn:hover,
.add-btn:hover {
  background: #ffd666 !important;
  color: #222 !important;
}
</style>
